package com.cn.main.proxy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.client.RestTemplate;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

/**
 * @aothor chenyuncong
 * @Date 2022/8/29 下午10:27
 */
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@ProxyBean(HttpClient.HttpClientProxyHandler.class)
public @interface HttpClient {
    @Target({ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @interface Request {
        String url();

        RequestMethod method() default RequestMethod.POST;
    }

    /**
     * 简单定义下进行测试,实际实现肯定要比这个复杂
     */
    class HttpClientProxyHandler implements ProxyHandler {
        /**
         * 这个类虽然没有被Spring管理,不过通过这个注解可以实现SpringBean的注入和使用,
         * 见ProxyFactoryBean构造方法的代码
         * SpringBean.inject(proxyHandler);
         */
        @Autowired
        private RestTemplate template;

        @Override
        public Object execute(Class<?> proxyType, Method proxyMethod, Object[] args) {

            return template.postForObject(
                    proxyMethod.getAnnotation(Request.class).url()
                    , args[0]
                    , proxyMethod.getReturnType()
            );
        }
    }
}
